package com.dcms.power.controller;

import com.dcms.power.annotation.ArchivesLog;
import com.dcms.admin.bean.User;
import com.dcms.admin.controller.BaseController;
import com.dcms.power.bean.Menu;
import com.dcms.power.bean.RoleMenu;
import com.dcms.power.service.IMenuService;
import com.dcms.power.service.IRoleMenuService;
import com.dcms.util.ResultBean;
import com.dcms.util.spider.WebSpider;
import com.dcms.util.layui.LayTable;
import com.dcms.util.layui.NavBar;
import com.dcms.util.ztree.ZTree;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * \*
 * \* @name: MenuController
 * \* @author: 武佳伟丶
 * \* @date: 2018/4/8 0008
 * \* @time: 19:23
 * \* @description: To change this template use File | Settings | File Templates.
 * \
 */
@Controller
@RequestMapping("power/menu")
public class MenuController extends BaseController {

    @Autowired
    private IMenuService menuService;
    @Autowired
    private IRoleMenuService roleMenuService;

    @RequestMapping("query")
    @ResponseBody
    public LayTable<Menu> query(
            String param,
            Menu record,
            Integer limit,
            Integer page
    ){
        page = page == null ? 1 : page;
        limit = limit == null ? 12 : limit;

        PageHelper.startPage(page, limit);
        List<Menu> list = menuService.selectAll(param, record);
        PageInfo<Menu> info = new PageInfo<Menu>(list);
        LayTable<Menu> bean = new LayTable<Menu>(info.getList(), (int)info.getTotal());
        return bean;
    }

    /**
     * @author: 武佳伟丶
     * @description: 获取我的菜单
     * @date: 10:32 2018/4/9 0009
     * @param: []
     * @return: java.util.List<com.dcms.util.layui.NavBar>
     */
    @RequestMapping("getMyNavBar")
    @ResponseBody
    public List<NavBar> getMyNavBar(){
        User user = getCurrentUser();
        int userId = user.getUserId();
        List<NavBar> firstLevels = null;
        String basePath = request.getContextPath();

        //查询出所有菜单
        List<Menu> menus = menuService.selectMenuByItemId(userId, null);
        if (menus.size() > 0){
            firstLevels = new ArrayList<NavBar>();

            for (Menu menu : menus){
                //先获取一级菜单
                int level = menu.getLevel();
                if (level == 1){
                    NavBar navBar = new NavBar();
                    navBar.setId(menu.getMenuId() + "");
                    navBar.setIcon(menu.getIcon());
                    navBar.setTitle(menu.getTitle());
                    navBar.setSpread(false);
                    String url = menu.getUrl();
                    if (!"/".equals(url)){
                        navBar.setUrl(basePath + url);
                    }
                    firstLevels.add(navBar);
                }
            }

            //循环一级菜单，与所有菜单匹配pid，填充子菜单
            for (NavBar firstLevel : firstLevels){
                //获取pid
                int pid = Integer.valueOf(firstLevel.getId());
                //初始化子菜单
                List<NavBar> childrenLevels = new ArrayList<NavBar>();
                //遍历所有菜单
                for (Menu menu : menus){
                    int id = menu.getMenuId();
                    int pid_tmp = menu.getPid();
                    if (pid_tmp == pid){
                        NavBar child = new NavBar();
                        child.setId(id + "");
                        child.setUrl(basePath + menu.getUrl());
                        child.setTitle(menu.getTitle());
                        child.setIcon(menu.getIcon());
                        child.setSpread(false);
                        //添加到子菜单集合中
                        childrenLevels.add(child);
                    }
                }
                //将完整的子菜单添加到一级菜单中
                firstLevel.setChildren(childrenLevels);
            }
        }

        return firstLevels;
    }

    @RequestMapping("getMenuTree")
    @ResponseBody()
    public List<ZTree> getMenuTree(Integer roleId){
        List<ZTree> zTreeList = null;

        //查询出所有菜单
        List<Menu> menus = menuService.selectMenuByItemId(null, null);
        if (menus.size() > 0) {

            //获取该角色拥有的菜单
            List<Integer> checkedMenuIds = new ArrayList<Integer>();
            RoleMenu roleMenuRecord = new RoleMenu();
            roleMenuRecord.setRoleId(roleId);
            List<RoleMenu> roleMenuList = roleMenuService.selectAll(null, roleMenuRecord);
            if (roleMenuList.size() > 0){
                //提取menuId
                for (RoleMenu roleMenu : roleMenuList) {
                    int menuId = roleMenu.getMenuId();
                    checkedMenuIds.add(menuId);
                }
            }


            zTreeList = new ArrayList<ZTree>();
            for (Menu menu : menus) {
                //先获取一级菜单
                int level = menu.getLevel();
                if (level == 1) {
                    int menuId = menu.getMenuId();
                    ZTree zTree = new ZTree();
                    zTree.setName(menu.getTitle());
                    zTree.setOpen(false);
                    zTree.setTitle(menu.getMenuId() + "");
                    zTree.setId(menuId);
                    if (checkedMenuIds.contains(menuId)){
                        zTree.setChecked(true);
                    }
                    zTree.setLevel(menu.getLevel());
                    zTree.setDrag(false);
                    zTreeList.add(zTree);
                }
            }

            //循环一级菜单，与所有菜单匹配pid，填充子菜单
            for (ZTree zTree : zTreeList) {
                //获取pid
                int pid = Integer.valueOf(zTree.getId());
                //初始化子菜单
                List<ZTree> children = new ArrayList<ZTree>();
                //遍历所有菜单
                for (Menu menu : menus) {
                    int id = menu.getMenuId();
                    int pid_tmp = menu.getPid();
                    if (pid_tmp == pid) {
                        ZTree child = new ZTree();
                        child.setName(menu.getTitle());
                        child.setOpen(false);
                        child.setTitle(menu.getMenuId() + "");
                        if (checkedMenuIds.contains(menu.getMenuId())){
                            child.setChecked(true);
                        }
                        child.setId(id);
                        child.setLevel(menu.getLevel());
                        zTree.setDrag(false);
                        children.add(child);
                    }
                }
                //将完整的子菜单添加到一级菜单中
                zTree.setChildren(children);
            }
        }

        return zTreeList;
    }

    /**
     * @author: 武佳伟丶
     * @description: 删除
     * @date: 14:39 2018/2/12 0012
     * @param: [id]
     * @return: com.dcms.util.ResultBean
     */
    @ArchivesLog(message = "删除菜单")
    @RequestMapping("delete")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public ResultBean deleteBatch(Integer id, boolean isParent){
        int rows = 0;
        //检查该节点是否父节点
        if (isParent){
            rows = menuService.deleteByPid(id);
        }
        rows += menuService.deleteByPrimaryKey(id);
        if (rows > 0){
            return new ResultBean();
        }
        return new ResultBean(10021);
    }

    /**
     * @author: 武佳伟丶
     * @description: 更新
     * @date: 18:55 2018/2/13 0013
     * @param: [record]
     * @return: com.dcms.util.ResultBean
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    @ArchivesLog(message = "更新菜单")
    public ResultBean update(Menu record){
        Date now = new Date();
        if (record.getLevel() == 2){
            int menuId = record.getMenuId();
            Menu oldRecord = menuService.selectByPrimaryKey(menuId);
            int oldLevel = oldRecord.getLevel();
            //说明本次更新是由父节点改为子节点，那么需要同时修改它原先的所有子节点到新的父节点
            if (oldLevel == 1){
                //先检查有无子节点
                Menu paramMenu = new Menu();
                paramMenu.setPid(menuId);
                List<Menu> menuList = menuService.selectAll(null, paramMenu);
                if (menuList.size() > 0){
                    for (Menu m : menuList){
                        //更新子节点到新的父节点
                        m.setPid(record.getPid());
                        menuService.updateByPrimaryKeySelective(m);
                    }
                }
            }
        }


        record.setUpdateTime(now);
        int rows = menuService.updateByPrimaryKeySelective(record);
        if (rows > 0){
            return new ResultBean();
        }
        return new ResultBean(10021);
    }

    /**
     * @author: 武佳伟丶
     * @description: 跳转到数据编辑页，用于新增数据
     * @date: 14:42 2018/2/18 0018
     * @param: [menuId, request]
     * @return: java.lang.String
     */
    @RequestMapping("detail")
    @ResponseBody
    public ResultBean detail(Integer menuId){
        Menu record = menuService.selectByPrimaryKey(menuId);
        return new ResultBean(10000, "success", record);
    }

    /**
     * @author: 武佳伟丶
     * @description: 录入数据
     * @date: 14:52 2018/2/18 0018
     * @param: [record]
     * @return: com.dcms.util.ResultBean
     */
    @RequestMapping("insert")
    @ResponseBody
    @ArchivesLog(message = "添加菜单")
    public ResultBean insert(Menu record){
        Date now = new Date();
        record.setMenuId(null);
        record.setCtime(now);
        record.setUpdateTime(now);
        record.setCreator(getCurrentUser().getUserId());
        int rows = menuService.insertSelective(record);
        if (rows > 0){
            return  new ResultBean();
        }
        return new ResultBean();
    }

    /**
     * @author: 武佳伟丶
     * @description: 抓取layui图标库图标编码
     * @date: 14:28 2018/4/12 0012
     * @param: []
     * @return: com.dcms.util.ResultBean
     */
    @RequestMapping("icons")
    @ResponseBody
    public ResultBean getLayUIIcons(){
        //抓取layui图标库图标编码
        List<String> icons = WebSpider.getWebData(
                "http://www.layui.com/doc/element/icon.html",
                "<div class=\"code\">(.+?)</div>");
        if (icons.size() > 0){
            return new ResultBean(10000, "success", icons);
        }
        return new ResultBean(101, "fail", null);
    }

}